/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package validator;

import java.util.regex.Pattern;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import pojo.DonDatHang;

/**
 *
 * @author MongKieu
 */
public class ThongTinKhachHangValidator implements Validator {

    private final static Pattern EMAIL_PATTERN = Pattern.compile(".+@.+\\.[a-z]+");

    @Override
    public boolean supports(Class<?> type) {
        return DonDatHang.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "khachHang.hoTen", "tenKhach.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "khachHang.diaChi.tenDiaChi", "diaChi.required");
        DonDatHang donDatHang = (DonDatHang) o;
        if (!isEmail(donDatHang.getKhachHang().getEmail())) {
            errors.rejectValue("khachHang.email", "email.required");
        }
        String email = donDatHang.getKhachHang().getEmail();
        String confirmEmail = donDatHang.getKhachHang().getXacNhanEmail();
        if (email.equals(confirmEmail) == false) {
            errors.rejectValue("khachHang.xacNhanEmail", "confirmEmail.required");
        }
    }

    private boolean isEmail(String value) {
        return EMAIL_PATTERN.matcher(value).matches();
    }
}
